#include "head.h"

int Mkdir(int netfd,char* addr,char* dirname){
    int length=strlen(addr)+strlen(dirname)+1;
    char* realDir=(char*)malloc(length);
    sprintf(realDir,"%s/%s",addr,dirname);//拼接字符串 
    int ret = mkdir(realDir,0777);
    //NETDISK_LOG_INFO(1,1,"mkDir");

    train_t train;
    bzero(&train,sizeof(train));
    if(ret==-1){
        sprintf(train.data,"mkdir:创建%s目录失败！",dirname);
        train.length = strlen(train.data);
        send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);

     //   NETDISK_LOG_ERR(1,1,"mkdir");
    }
    else{
        sprintf(train.data,"mkdir:创建%s目录成功！",dirname);
        train.length = strlen(train.data);
        send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);
    }
    
    return 0;
}

int Rmdir(int netfd,char* addr,char *dirname){
    int length=strlen(addr)+strlen(dirname)+1;
    char* realDir=(char*)malloc(length);
    sprintf(realDir,"%s/%s",addr,dirname);//拼接字符串 
    
    DIR *dir = opendir(realDir);
    struct dirent *pdirent;
    if(dir==NULL){
        printf("错误的路径！\n");
        exit(1);
      //  NETDISK_LOG_ERR(1,1,"rmdir");
        return -1;
    }

    char path[1024];
    while((pdirent=readdir(dir))!=NULL){
        if(!strcmp(pdirent->d_name,".")||!strcmp(pdirent->d_name,"..")){
            continue;
        }
        snprintf(path,1024,"%s/%s",realDir,pdirent->d_name);
        if(pdirent->d_type==DT_DIR){
            Rmdir(0,path,"");
        }
        else{
            unlink(path);
        }
    }
    closedir(dir);

    rmdir(realDir);

    train_t train;
    bzero(&train,sizeof(train));
    sprintf(train.data,"rmdir:删除%s目录成功！",dirname);
    train.length = strlen(train.data);
    send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);
    
    return 0;
}

int Remove(int netfd,char *addr,char *dirname){
    int length=strlen(addr)+strlen(dirname)+1;
    char* realDir=(char*)malloc(length);
    sprintf(realDir,"%s/%s",addr,dirname);//拼接字符串 
    
    int ret=unlink(realDir);
    ERROR_CHECK(ret,-1,"Removeunlink");
    train_t train;
    bzero(&train,sizeof(train));
  //  NETDISK_LOG_INFO(1,1,"Remove");

    if(ret==-1){
        sprintf(train.data,"rm:无法删除%s文件!",dirname);
        train.length=strlen(train.data);
        send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);
        NETDISK_LOG_ERR(1,1,"Remove");
    }
    else{
        sprintf(train.data,"rm:删除%s文件成功！",dirname);
        train.length=strlen(train.data);
        send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);
        
    }
    return 0;
}

int pwd(int netfd,char *addr,char *dirname){
    train_t train;
    bzero(&train,sizeof(train));
    sprintf(train.data,"当前路径是/%s",dirname);
    train.length=strlen(train.data);
    send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);
    return 0;
}
